package com.mapaower.project.service.impl;

import com.mapaower.project.dao.ProjectRepository;
import com.mapaower.project.entity.Project;
import com.mapaower.project.service.ProjectService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

/**
 * 项目服务实现类
 * 实现项目相关的业务逻辑
 */
@Service
public class ProjectServiceImpl implements ProjectService {

    @Autowired
    private ProjectRepository projectRepository;

    @Override
    public Project createProject(Project project) {
        // 设置默认状态为开放
        project.setStatus(Project.ProjectStatus.OPEN);
        return projectRepository.save(project);
    }

    @Override
    public Project updateProject(Project project) {
        return projectRepository.save(project);
    }

    @Override
    public Optional<Project> getProjectById(Long id) {
        return projectRepository.findById(id);
    }

    @Override
    public List<Project> getProjectsByCreatorId(Long creatorId) {
        return projectRepository.findByCreatorId(creatorId);
    }

    @Override
    public List<Project> getOpenProjects() {
        return projectRepository.findByStatus(Project.ProjectStatus.OPEN);
    }

    @Override
    public List<Project> getProjectsByTypeAndStatus(Project.ProjectType type, Project.ProjectStatus status) {
        return projectRepository.findByTypeAndStatus(type, status);
    }

    @Override
    public List<Project> searchProjects(String keyword) {
        return projectRepository.findByTitleContainingOrDescriptionContaining(keyword, keyword);
    }

    @Override
    public Project updateProjectStatus(Long id, Project.ProjectStatus status) {
        Optional<Project> optionalProject = projectRepository.findById(id);
        if (optionalProject.isPresent()) {
            Project project = optionalProject.get();
            project.setStatus(status);
            return projectRepository.save(project);
        }
        throw new RuntimeException("Project not found with id: " + id);
    }

    @Override
    public void deleteProject(Long id) {
        projectRepository.deleteById(id);
    }
}